'use strict';
const db = uniCloud.database()
const uniID = require('uni-id')
exports.main = async (param, context) => {
	//event为客户端上传的参数
	let event = {}
	if(param.body==undefined){
		event = param
	}else{
		event = JSON.parse(param.body)
	}
	console.log('event:', event)
	let res = {}
	if(event.check){
		res = await checkToken(event)
	}else{
		res.code = 200
	}
	if (!event.check||res.code == 200) {
		let url = event.url;
		let action = event.action;
		let data = event.data;
		let token = event.uniIdToken;
		// 加载业务函数
		let controller;
		try {
			controller = require(__dirname + '/controller/' + url); // __dirname是为了兼容阿里云
		} catch (err) {
			return {
				code: 402,
				msg: '请求错误: Request error',
			}
		}
		// 执行业务函数
		res = await controller.main({
			res,
			token,
			data,
			action
		});
	}
	//返回数据给客户端
	return res
};

async function checkToken(e) {
	var res = {
		code: 200,
		data: {}
	}
	if(e.check){
		let tokenRes = await uniID.checkToken(e.uniIdToken);
		console.log(tokenRes)
		if (tokenRes.code>0) {
			res.code = 401;
			res.msg = tokenRes.msg;
		}
	}
	return res
}
